package com.mrdeer.web.controller.sys;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mrdeer.common.JSONResult;
import com.mrdeer.common.entity.dto.StopWordDTO;
import com.mrdeer.common.entity.sys.StopWord;
import com.mrdeer.utils.StopWordsUtil;
import com.mrdeer.web.service.sys.SysStopWordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@RestController
@Api(tags = "禁用词管理接口")
@RequestMapping("/mrdeer/stopWord")
@Transactional
public class SysStopWordController {

    @Resource
    private SysStopWordService sysStopWordService;

    @RequestMapping(value = "/getByCondition", method = RequestMethod.POST)
    @ApiOperation(value = "多条件分页获取")
    public JSONResult getByCondition(@RequestBody StopWordDTO stopWord) {
        try {
            Page<StopWord> page = sysStopWordService.list(stopWord);
            return JSONResult.ok(page);
        } catch (Exception e) {
            return JSONResult.errorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "更新数据")
    public JSONResult save(@RequestBody StopWord stopWord) {
        sysStopWordService.add(stopWord);
        StopWordsUtil.addWord(stopWord.getTitle());
        return JSONResult.ok("保存成功");
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ApiOperation(value = "更新数据")
    public JSONResult update(@RequestBody StopWord stopWord) {
        StopWord old = sysStopWordService.getById(stopWord.getId());
        sysStopWordService.updateById(stopWord);
        StopWordsUtil.removeWord(old.getTitle());
        StopWordsUtil.addWord(stopWord.getTitle());
        return JSONResult.ok("更新成功");
    }

    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @ApiOperation(value = "批量通过Id删除")
    public JSONResult delByIds(@RequestParam String[] ids) {
        for (String id : ids) {
            StopWord stopWord = sysStopWordService.getById(id);
            sysStopWordService.removeById(id);
            StopWordsUtil.removeWord(stopWord.getTitle());
        }
        return JSONResult.ok("批量通过id删除数据成功");
    }
}
